package org.gitos.cloud;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.gitos.cloud.comet.tcp.TcpBootstrap;
import org.gitos.cloud.domain.comm.Constant;
import org.gitos.cloud.util.ZkUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.support.GenericApplicationContext;

/**
 * Created by shizhengchu on 16/3/1.
 */
@SpringBootApplication
public class Application implements CommandLineRunner {
    private static final Logger log = LoggerFactory.getLogger(Application.class);

    @Autowired
    GenericApplicationContext context;

    private static String mode = Constant.MODE_PROD;

    @Autowired
    private TcpBootstrap tcpBootstrap;
    private final int threadNum = 1;
    private final ExecutorService localThreadPool = Executors.newFixedThreadPool(threadNum);
    private Future tcpFuture = null;


    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    public void run(String... args) throws Exception {
        Application.mode = context.getEnvironment().getProperty(Constant.MODE_KEY, Constant.MODE_PROD);
        ZkUtil.init(context.getEnvironment().getProperty(Constant.ZK_HOSTS, ""), context.getEnvironment().getProperty(Constant.zk_PATH, "/register"));
        Runtime.getRuntime().addShutdownHook(new ShutdownHook());
        startupServer();
    }

    private void startupServer() {
        tcpFuture = localThreadPool.submit(tcpBootstrap);
        long timeout = 0L;
        tcpBootstrap.waitForStartup(timeout);
    }


    class ShutdownHook extends Thread {
        @Override
        public void run() {
            super.run();
            if (tcpFuture != null) {
                tcpFuture.cancel(true);
            }
            log.info("shutdown hook");
        }
    }
}


